package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    //查询全部方法
    @RequestMapping("/list")
    public String list(Model model, EmployeeQueryObject qo) {
        PageInfo pageResult = employeeService.query(qo);
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("pageResult", pageResult);
        model.addAttribute("departments", departments);
        model.addAttribute("qo", qo);
        return "employee/list";
    }

    //处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                employeeService.deleteByPrimaryKey(id);
            }
            return new JsonResult(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "删除失败");
        }

    }

    //新增 或 修改
    @RequestMapping("/input")
    public String input(Long id, Model model) {

        List<Role> roles = roleService.selectAll();
        model.addAttribute("roles", roles);

        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);
        if (id != null) {
            //表示去修改
            Employee employee = employeeService.selectByPrimaryKey(id);
            model.addAttribute("employee", employee);
        }
        return "employee/input";// 让 浏览器重新 发一次请求 跳转到input 页面
    }

    // 新增 或 修改
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids) {
        try {
            if (employee.getId() != null) {
                //新增
                employeeService.updateByPrimaryKey(employee, ids);
            } else {
                employeeService.insert(employee, ids);
            }
            return new JsonResult(true, "保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "保存失败");
        }
    }

    // 修改密码
    @RequestMapping("/updatePwd")
    public String updatePwd(String oldPassword, String newPassword) {
        return "updatepwd/updatePwd";
    }

    // 修
    @RequestMapping("/updateing")
    @ResponseBody
    public JsonResult updateing(String oldPassword, String newPassword) {

        //System.out.println(oldPassword);
        //System.out.println(newPassword);

        try {
            employeeService.updatePassword(oldPassword, newPassword);
            return new JsonResult(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, e.getMessage());
        }

    }

    //重置密码

    // 修改密码
    @RequestMapping("/reset")
    public String resetPwd(Long id, Model model) {
        Employee employee = employeeService.selectByPrimaryKey(id);
        model.addAttribute("employee", employee);
        return "resetpwd/resetPwd";
    }

    @RequestMapping("/reseting")
    @ResponseBody
    public JsonResult reseting(String newPassword, Long id, Model model) {
        // Employee employee = UserContext.getCurrentUser();
        // model.addAttribute("CurrentUser",employee);
        //System.out.println(employee);
        try {
            employeeService.resetPassword(newPassword, id);
            return new JsonResult(true, "恭喜您 , 重置成功 !");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, e.getMessage());
        }
        //测试专用
        //System.out.println(id);
        //System.out.println(newPassword);

    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(@RequestParam("ids[]") Long[] ids) {
        try {
            if (ids != null && ids.length > 0) {
                employeeService.batchDelete(ids);
            }
            return new JsonResult(true, "恭喜您 , 删除成功 !");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "删除失败");
        }
    }

    //checkName  的方法
    @RequestMapping("/checkName")
    @ResponseBody
    public Map checkName(String name, Long id) {
        Employee employee = employeeService.selectByName(name);
        //定义一个map 看他的后台案例的 返回的是一个 key和value  key是固定的  valid
        HashMap<String, Boolean> map = new HashMap<>();
        if (id != null) {

            Employee employee1 = employeeService.selectByPrimaryKey(id);
            String name1 = employee1.getName();


            if (name1.equals(name)) {
                map.put("valid", true);
            }
            return map;
        } else {
            map.put("valid", employee == null);
            return map;
        }
//        if(employee!=null){
//            //如果能查到,说明本来就有这个用户了 , 所以返回false
//            map.put("valid",false);
//        }else{
//            map.put("valid",true);
//        }
    }

    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件下载的响应头 (让浏览器访问的时候以下载的方式打开)
        response.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        //创建 excel 文件
        Workbook wb = new HSSFWorkbook();
        //创建 sheet  员工表单
        Sheet sheet = wb.createSheet("员工表单");
        //创建标题行
        Row row = sheet.createRow(0);
        //设置内容到单元格
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> employees = employeeService.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            //获取 当前遍历的员工
            Employee employee = employees.get(i);
            //创建行(每个员工就是一行)
            row = sheet.createRow(i + 1);
            //设置内容到 单元格中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            //  记得 要 判断  null的问题   否则空指针异常
            if (employee.getAge() != null) {
                row.createCell(2).setCellValue(employee.getAge());
            }
        }
        //把 excel 的数据输出给浏览器
        wb.write(response.getOutputStream());
    }


    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {

        employeeService.importXls(file);
        return new JsonResult(true,"成功");
    }


}
